using CxRomos.Core.DataAccess;
using CxRomos.Core.Services;
using CxRomos.Core.Services.Implementation;
using CxRomos.Web.Account.Interface;
using StructureMap;

namespace CxRomos.Web.Account.Presenter {
    public class EditAccountPresenter {
        private IEditAccount _view;
        private readonly IUserSession _userSession;
        private readonly IAccountService _accountService;
        private readonly IAccountRepository _accountRepository;
        private Core.Domain.Entities.Account _account;
        private readonly IRedirector _redirector;
        private readonly IEmail _email;

        public EditAccountPresenter() {
            _userSession = ObjectFactory.GetInstance<IUserSession>();
            _accountRepository = ObjectFactory.GetInstance<IAccountRepository>();
            _redirector = ObjectFactory.GetInstance<IRedirector>();
            _accountService = ObjectFactory.GetInstance<IAccountService>();
            _email = ObjectFactory.GetInstance<IEmail>();
        }

        public void Init(IEditAccount view) {
            _view = view;

            if (_userSession.CurrentUser != null) {
                _account = _userSession.CurrentUser;
            } else {
                _redirector.GoToAccountLoginPage();
            }
        }

        public void LoadCurrentUser() {
            _view.LoadCurrentInformation(_userSession.CurrentUser);
        }

        public void UpdateAccount(string oldPassword, string newPassword, string firstName, string lastName, string email) {
            if (Cryptography.Encrypt(oldPassword, email.Split('@')[0]) == _account.Password) {
                if (email != _userSession.CurrentUser.Email) {
                    if (_accountService.EmailInUse(email)) {
                        _account.Email = email;
                        _account.EmailVerified = true;
                        _email.SendEmailAddressVerificationEmail(_account.Email, email);
                    }
                    else {
                        _view.ShowMessage("The email you entered is already in our system");
                    }
                }

                if (!string.IsNullOrEmpty(newPassword)) {
                    _account.Password = Cryptography.Encrypt(newPassword, email.Split('@')[0]);
                }

                _account.FirstName = firstName;
                _account.LastName = lastName;
                _account.Email = email;

                _accountRepository.SaveAccount(_account);
                _view.ShowMessage("Your account has been updated");
            } else {
                _view.ShowMessage("The password you entered does not match your current password! Please try again.");
            }
        }
    }
}